package top.pmwly.oauth2.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;
import top.pmwly.oauth2.service.UserService;

import javax.annotation.Resource;

/**
 * @author Herther
 * @version 1.0.0
 * @ClassName AuthenticationServerConfig.java
 * @Description 认证服务器配置类
 * @createTime 2021年08月22日 15:18:00
 */
@Configuration
@EnableAuthorizationServer
public class AuthenticationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private UserService userService;
    @Autowired
    @Qualifier("redisTokenStore")
    private TokenStore tokenStore;
    @Autowired
    private RedisConnectionFactory redisConnectionFactory;


    /**
     * 重写 configure方法
     * @param clients
     * @throws Exception
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {

        clients.inMemory()
                //客户端id，方便演示放入内存
                .withClient("admin")
                //客户端秘密吗，方便演示放入内存
                .secret(passwordEncoder.encode("666"))
                //token 失效时间
                .accessTokenValiditySeconds(3600)
                //授权范围
                .scopes("all")
                //授权类型 为密码授权
                .authorizedGrantTypes("password");

    }

    /**
     * 密码模式配置
     * @param endpoints
     * @throws Exception
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        //授权管理器
        endpoints.authenticationManager(authenticationManager)
                //自定义登录逻辑
                .userDetailsService(userService)
                //把token 放入大redis中
                .tokenStore(tokenStore);
    }






}
